package com.ijava.taglib;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class UIMessageTaglib extends TagSupport {
	private String code;
	private String isError;
	
	public String getCode(HttpSession session) {
		MessageSource messageSource = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext()).getBean(ResourceBundleMessageSource.class);
		return messageSource.getMessage(code, null,"", Locale.getDefault());
	}

	public void setCode(String code) {
		this.code = code;
	}

	@Override
	public int doEndTag() throws JspException {
		
		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
		HttpSession session = request.getSession(true);
		if(!StringUtils.hasLength(getCode(session))){
			return super.doEndTag();
		}
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("<div class='ui-widget'>");
		if("true".equalsIgnoreCase(getIsError()) || "1".equalsIgnoreCase(getIsError())){
			buffer.append("<div class='ui-state-error ui-corner-all' style='padding: 0 .7em;'> ");
			buffer.append("<p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>");
		} else {
			buffer.append("<div class='ui-state-highlight ui-corner-all' style='margin-top: 20px; padding: 0 .7em;'> ");
			buffer.append("<p><span class='ui-icon ui-icon-info' style='float: left; margin-right: .3em;'></span>");
		}		
		buffer.append(getCode(session));
		buffer.append("</p>");
		buffer.append("</div>");
		buffer.append("</div>");
		try {
			pageContext.getOut().print(buffer.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}

	public String getIsError() {
		return isError;
	}

	public void setIsError(String isError) {
		this.isError = isError;
	}


	
}
